<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Models\Mongodb;
use App\Models\MyLog;
require_once 'code/Code.class.php';
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest.admin', ['except' => 'logout']);
    }

    /**
     * 显示后台登录模板
     */
    public function showLoginForm()
    {
        return view('admin.login');
    }

    //验证码
    public function code()
    {
        $code = new \Code;
        $code->make();
    }

    /**
     * 使用 admin guard
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }

    /**
     * 重写验证时使用的用户名字段
     */
    public function username()
    {
        return 'name';
    }


//在这里重新进行验证
    public function login(Request $request)
    {

        $code = new \Code;
        $_code = $code->get();
        if (strtoupper($request->code) != $_code) {
            return back()->with('msg', '验证码错误!');
        }


        $this->validate($request, [
            'name' => 'required|min:2',
            'password' => 'required|min:6|max:30',
        ]);

        $user = request(['name', 'password']);
        if (true == \Auth::guard('admin')->attempt($user)) {

            $mylog = new MyLog;
            $mylog->setLog($request->name.'登陆了后台：', $logPath = 'adminLogin');
            return redirect('/camelredadmin');
        }
        return redirect('/camelredadmin/login');
    }


    // 退出
    public function logout(Request $request)
    {
        \Auth::guard('admin')->logout();
        return redirect('/camelredadmin/login');
    }
}